package com.cloud.lan.entity.utils;

import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;

/**
 * 订单编号的生成工具类
 * @author ErKang
 * @date Created in 2021/12/21 11:16
 * @title OrderNoUtils.java
 * Department: Product development
 */
public class OrderNoUtils {

    private static final String DATETIME = "yyyyMMddHHmmssSSS";
    private static final String IDX = "%04d";
    private static final ThreadLocal<SimpleDateFormat> SDF_THREAD_LOCAL = ThreadLocal.withInitial(()
            -> new SimpleDateFormat(DATETIME));
    private static NumberFormat NF = NumberFormat.getInstance();

    static {
        NF.setMinimumIntegerDigits(6);
        NF.setMaximumIntegerDigits(6);
        NF.setGroupingUsed(false);
    }

    /**
     * Description: [ 订单编号,(时间格式时间戳17位)20210722122012333 + 随机数4 + 用户id后6位 =27位 ]
     * @param userId
     * @return java.lang.String
     * 2021/11/4 17:20
     */
    public static String generateOrderNo(Long userId) {
        SimpleDateFormat simpleDateFormat = SDF_THREAD_LOCAL.get();
        if (Objects.isNull(simpleDateFormat)) {
            simpleDateFormat = new SimpleDateFormat(DATETIME);
            SDF_THREAD_LOCAL.set(simpleDateFormat);
        }
        StringBuilder sb = new StringBuilder();
        sb.append(simpleDateFormat.format(new Date()))
                .append(String.format(IDX, RandomUtil.randomInt(10000)))
                .append(NF.format(userId));
        return sb.toString();
    }

    public static void main(String[] args) {
        String littaOrder = StrUtil.format("{}", OrderNoUtils.generateOrderNo(21339851L));
        System.out.println(littaOrder);
//        System.out.println(generateOrderNo(21340256L));
    }
}
